package com.ideal.service.impl;

import com.ideal.constant.LocalPathConstant;
import com.ideal.proxy.TocProxy;
import com.ideal.proxy.entity.DocRequest;
import com.ideal.proxy.entity.TocRequest;
import com.ideal.proxy.impl.DocProxyImpl;
import com.ideal.proxy.impl.TocProxyImpl;
import com.ideal.request.ExportDocRequest;
import com.ideal.request.LocalPathRequest;
import com.ideal.response.BaseResponse;
import com.ideal.service.ExportDocService;
import com.ideal.service.RefactorMarkdownService;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.util.Assert;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * <h1> 导出 markdown 业务实现类 </h1>
 *
 * @author ideal-20
 * @date 2023-08-04 23:30
 **/
public class ExportDocServiceImpl implements ExportDocService {

    /**
     * 导出 doc 次数（仅单线程串行可用）
     */
    private static int EXPORT_DOC_COUNT = 0;

    @Test
    public void test() {
        BaseResponse<String> response = exportAllDocOfRepo(new ExportDocRequest(null, "xxx", "ideal-20/java-ideal-interview", System.getProperty("user.home") + "/Desktop/语雀导出"));
        System.out.println(response);
    }

    /**
     * <h2> 导出知识库下的全部文档 </h2>
     */
    @Override
    public BaseResponse<String> exportAllDocOfRepo(ExportDocRequest request) {
        if (request == null
                || StringUtils.isBlank(request.getToken())
                || StringUtils.isBlank(request.getRepoNamespace())
                || StringUtils.isBlank(request.getExportLocalDirPath())) {
            return BaseResponse.fail("参数错误");
        }

        long exportStartTime = System.currentTimeMillis();

        String tocResp = new TocProxyImpl().getTocOfRepo(new TocRequest(request.getApiUrl(), request.getToken(), null, request.getRepoNamespace()));
        if (StringUtils.isBlank(tocResp) || !tocResp.contains("data")) {
            return BaseResponse.fail("tocResp 异常");
        }
        exportAllDocByToc(tocResp, request);

        long exportEndTime = System.currentTimeMillis();

        RefactorMarkdownService refactorMarkdownService = new RefactorMarkdownServiceImpl();
        LocalPathRequest localPathReq = new LocalPathRequest();
        localPathReq.setLocalPath(request.getExportLocalDirPath());
        localPathReq.setPathType(LocalPathConstant.DIR_PATH);
        localPathReq.setDirRecursive(1);
        String refactorResp = refactorMarkdownService.doRefactorLocalForGui(localPathReq);

        String resultLog = "---------整体详情---------"
                + "\n" + "整体耗时：" + (System.currentTimeMillis() - exportStartTime) + " ms"
                + "\n" + "文件数量：" + EXPORT_DOC_COUNT + "\n"
                + "\n" + "---------导出详情---------"
                + "\n" + "在线导出文件数量：" + EXPORT_DOC_COUNT
                + "\n" + "在线导出文件耗时：" + (exportEndTime - exportStartTime) + " ms"  + "\n"
                + "\n" + "---------重构详情---------";
        resultLog += refactorResp;

        System.out.println(resultLog);

        return BaseResponse.success(resultLog);
    }

    public void exportAllDocByToc(String tocResp, ExportDocRequest request) {
        JSONObject resultObj = JSONObject.parseObject(tocResp);
        JSONArray jsonArray = resultObj.getJSONArray("data");
        String outputDir = request.getExportLocalDirPath();

        // 创建根文件夹
        File rootFolder = new File(outputDir);
        if (!rootFolder.exists()) {
            rootFolder.mkdir();
        }

        // 遍历 JSON 数组，生成文件夹和文件
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String type = jsonObject.getString("type");
            String title = jsonObject.getString("title");
            String slug = jsonObject.getString("slug");
            String content = ""; // 这里填写你获取到的文章内容

            if (type.equals("TITLE")) {
                // 如果是分组标题，则创建对应的文件夹
                File folder = new File(outputDir + "/" + title);
                if (!folder.exists()) {
                    folder.mkdir();
                }
            } else if (type.equals("DOC")) {
                // 如果是文章，则生成对应的 markdown 文件
                File folder = new File(outputDir + "/" + getFolderPath(jsonArray, slug));
                if (!folder.exists()) {
                    folder.mkdirs();
                }

                String finalTitle = title;
                finalTitle = finalTitle.replaceAll("/", "或");

                File file = new File(folder.getPath() + "/" + finalTitle + ".md");
                try {
                    content = new DocProxyImpl().getDocBySlug(new DocRequest(request.getApiUrl(), request.getToken(), null, request.getRepoNamespace(), slug));
                    if (StringUtils.isNotBlank(content)) {
                        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
                        // 将 <a> 和 </a > 标签替换为空字符串
                        content = content.replaceAll("<a[^>]*>|<\\/a>", "");
                        // 将换行符替换为 Windows 系统下的换行符
                        content = content.replace("\\n", "\n");
                        writer.write(content);
                        writer.close();
                        EXPORT_DOC_COUNT++;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * <h2> 获取最终文件夹的相对路径 </h2>
     */
    private static String getFolderPath(JSONArray jsonArray, String slug) {
        List<String> folderNames = new ArrayList<>();
        JSONObject jsonObject = getJSONObjectBySlug(jsonArray, slug);
        while (jsonObject != null) {
            String title = jsonObject.getString("title");
            folderNames.add(0, title);
            String parentUuid = jsonObject.getString("parent_uuid");
            jsonObject = getJSONObjectByUuid(jsonArray, parentUuid);
        }
        if (folderNames.size() >= 2) {
            folderNames.remove(folderNames.size() - 1);
        }
        return String.join("/", folderNames);
    }

    /**
     * <h2> 寻找指定 slug 的信息 </h2>
     */
    private static JSONObject getJSONObjectBySlug(JSONArray jsonArray, String slug) {
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if (jsonObject.getString("slug").equals(slug)) {
                return jsonObject;
            }
        }
        return null;
    }

    /**
     * <h2> 寻找指定 uuid 的信息 </h2>
     */
    private static JSONObject getJSONObjectByUuid(JSONArray jsonArray, String uuid) {
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if (jsonObject.getString("uuid").equals(uuid)) {
                return jsonObject;
            }
        }
        return null;
    }

}